package com.kevin.j2eeToolBox.lock;

public class SynchronizedTest2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Example1 example = new Example1();
		Thread3 thread1 = new Thread3(example);
		Thread4 thread2 = new Thread4(example);

		thread1.start();
		thread2.start();
	}
}

class Example1 {

	private Object obejct = new Object();

	public void execute1() {

		synchronized (obejct) {

			for (int i = 0; i < 20; i++) {
				try {
					Thread.sleep((long) (Math.random() * 1000));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				System.out.println("hello: " + i);
			}
		}
	}

	public void execute2() {

		synchronized (obejct) {
			for (int i = 0; i < 20; i++) {
				try {
					Thread.sleep((long) (Math.random() * 1000));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				System.out.println("world: " + i);
			}
		}
	}
}

class Thread3 extends Thread {

	private Example1 example;

	public Thread3(Example1 example) {

		this.example = example;
	}

	@Override
	public void run() {
		this.example.execute1();
	}
}

class Thread4 extends Thread {

	private Example1 example;

	public Thread4(Example1 example) {

		this.example = example;
	}

	@Override
	public void run() {
		this.example.execute2();
	}
}
